package com.gzq.singleton.practice15;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 单例设计模式。在整个系统中，有且仅有一个对象会产生。
 * 
 * 确保一个类只有一个实例。
 * 
 * 饿汉式：静态常量版本、静态代码块版本。
 * 
 * 懒汉式：方法锁、双重校验锁、静态内部类、
 * 
 * 枚举。
 * 
 * @author Administrator
 *
 */
public class DCL15 implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args) throws NoSuchMethodException,
			SecurityException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IOException,
			ClassNotFoundException {
		DCL15 singleton1 = DCL15.getSingleton();
		DCL15 singleton2 = DCL15.getSingleton();
		System.out.println(singleton1);
		System.out.println(singleton2);

		Constructor<DCL15> constructor = DCL15.class.getDeclaredConstructor();
		DCL15 singleton3 = constructor.newInstance();
		System.out.println(singleton3);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(singleton1);
		byte[] byteArray = baos.toByteArray();

		ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
		ObjectInputStream ois = new ObjectInputStream(bais);
		DCL15 readObject = (DCL15) ois.readObject();
		System.out.println(readObject);

	}

	private static DCL15 singleton;
	private static boolean isInitialize = false;

	private DCL15() {

	}

	public static DCL15 getSingleton() {
		if (!isInitialize) {
			synchronized (DCL15.class) {
				if (!isInitialize) {
					singleton = new DCL15();
					// 很多初始化的步骤。
					isInitialize = true;
				}
			}
		}
		return singleton;
	}

}
